package cn.wzx.dao;

import cn.wzx.entity.Blogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Repository
public class BlogDaoImpl implements BlogDao {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<Blogger> findBlogsByTypeId(String typeId) {
        Query query = new Query(Criteria.where("typeId").is(typeId));
        query.with(Sort.by(Sort.Order.desc("tpress")));//发表博客时间倒序
        List<Blogger> lst = mongoTemplate.find(query, Blogger.class);
        return lst;
    }

    @Override
    public void add(Blogger blogger) {
        mongoTemplate.save(blogger);
    }

    @Override
    public Blogger read(String blogId) {
        Query query = new Query(Criteria.where("id").is(blogId));
        return mongoTemplate.findOne(query,Blogger.class);
    }

    @Override
    public List<Blogger> findByTitle(String title) {
        System.out.println("tit==="+title);
        List<Blogger> lst = new ArrayList<>();
        if(title!=null&&!"".equals(title)){
            Criteria c = new Criteria();
            Pattern pattern = Pattern.compile("^.*"+title+".*$",Pattern.CASE_INSENSITIVE);
            c.and("title").regex(pattern);
            Query query = new Query(c);
            lst= mongoTemplate.find(query,Blogger.class);
        }
        return lst;
    }

    @Override
    public List<Blogger> fingBlogsByUid(String uid) {
        Query query = new Query(Criteria.where("uid").is(uid));
        return mongoTemplate.find(query,Blogger.class);
    }

    @Override
    public void del(String blogid) {
        Query query = new Query(Criteria.where("id").is(blogid));
        mongoTemplate.findAndRemove(query,Blogger.class);
    }

    @Override
    public Blogger findBlogById(String id) {
        return mongoTemplate.findById(id,Blogger.class);
    }
}
